package com.atguigu.flink.keyStateAndOpeState;

import com.atguigu.flink.bean.WaterSensor;
import com.atguigu.flink.function.WaterSensorMapFunction;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.state.AggregatingState;
import org.apache.flink.api.common.state.AggregatingStateDescriptor;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.util.Map;

/**
 *需求：统计每种传感器每种水位值出现的次数
 */

public class OperatorAggregatingState {
    public static void main(String[] args) throws Exception {
        // TODO 1.环境准备
        // 1.1指定流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        // 1.2设置并行度
        env.setParallelism(1);
        // TODO 2.从指定的网络端口读取数据
        DataStreamSource<String> socketDS = env.socketTextStream("hadoop102", 8888);
        // TODO 3.对数据进行类型转换 String -> Watersensor
        SingleOutputStreamOperator<WaterSensor> wsDS = socketDS.map(new WaterSensorMapFunction());
        // TODO 4.按照传感器id进行分组
        KeyedStream<WaterSensor, String> keyByDS = wsDS.keyBy(WaterSensor::getId);
        // TODO 5.对分组后的数据进行处理 判断连续的两个水位值是否超过10 如果超过10，输出报警
        SingleOutputStreamOperator<String> processDS = keyByDS.process(
                new KeyedProcessFunction<String, WaterSensor, String>() {

                    AggregatingState<Integer, Double> avgState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        AggregatingStateDescriptor<Integer, Tuple2<Integer, Integer>, Double> aggregatingStateDescriptor = new AggregatingStateDescriptor<>(
                                "",
                                new AggregateFunction<Integer, Tuple2<Integer, Integer>, Double>() {
                                    @Override
                                    public Tuple2<Integer, Integer> createAccumulator() {
                                        return Tuple2.of(0,0);
                                    }

                                    @Override
                                    public Tuple2<Integer, Integer> add(Integer vc, Tuple2<Integer, Integer> accumulator) {
                                        accumulator.f0 = accumulator.f0 + vc;
                                        accumulator.f1 = accumulator.f1 + 1;
                                        return accumulator;
                                    }

                                    @Override
                                    public Double getResult(Tuple2<Integer, Integer> accumulator) {
                                        Integer sum = accumulator.f0;
                                        Integer count = accumulator.f1;
                                        return sum * 1D / count;
                                    }

                                    @Override
                                    public Tuple2<Integer, Integer> merge(Tuple2<Integer, Integer> a, Tuple2<Integer, Integer> b) {
                                        return null;
                                    }
                                },
                                Types.TUPLE(Types.INT, Types.INT)
                        );
                        avgState = getRuntimeContext().getAggregatingState(aggregatingStateDescriptor);
                    }

                    @Override
                    public void processElement(WaterSensor ws, KeyedProcessFunction<String, WaterSensor, String>.Context ctx, Collector<String> out) throws Exception {
                        Integer vc = ws.getVc();
                        avgState.add(vc);
                        Double avg = avgState.get();
                        out.collect("传感器id为" + ctx.getCurrentKey() + "平均水位值" + avg);
                    }
                }
        );
        // TODO 6.打印输出
        processDS.print();
        // TODO 7.提交作业
        env.execute();
    }
}
